package com.example.treehole.fragmnet;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LifecycleOwner;
import androidx.viewpager2.widget.ViewPager2;

import com.example.treehole.R;
import com.example.treehole.activity.PublishActivity;
import com.example.treehole.activity.SettingActivity;
import com.example.treehole.adapter.ViewPage2Adapter;
import com.example.treehole.api.Api;
import com.example.treehole.api.ApiConfig;
import com.example.treehole.api.Callback;
import com.example.treehole.entity.TabEntity;
import com.example.treehole.entity.UserEntity;
import com.example.treehole.entity.UserResponse;
import com.example.treehole.widget.CircleImageView;
import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.view.listener.OnLvItemClickListener;
import com.squareup.picasso.Picasso;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;

public class fragment3 extends BaseFragment {

    @BindView(R.id.tab_layout)
    CommonTabLayout tabLayout;
    @BindView(R.id.view_page)
    ViewPager2 viewPage;
    @BindView(R.id.iv_background)
    ImageView ivBackground;
    @BindView(R.id.iv_header)
    CircleImageView ivHeader;
    @BindView(R.id.bar_layout)
    AppBarLayout barLayout;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_header_top)
    CircleImageView ivHeaderTop;
    @BindView(R.id.tv_name_top)
    TextView tvNameTop;

    private ArrayList<Fragment> mFragments = new ArrayList<>();
    ViewPage2Adapter adapter;
    private final ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    UserEntity userEntity;
    Bitmap bm;

    public static fragment3 newInstance() {
        return new fragment3();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragmen3;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void initData(View view) {
        //加载用户信息
        loadUser();
        //设置折叠事项
        barLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                //折叠
                if (Math.abs(verticalOffset) == appBarLayout.getTotalScrollRange()) {
                    toolbar.setVisibility(View.VISIBLE);
                } else if (verticalOffset == 0) {    //展开
                    toolbar.setVisibility(View.GONE);
                } else {
                    toolbar.setVisibility(View.GONE);
                }
            }
        });
        //设置背景图片
        String filePath = getContext().getFilesDir().getAbsolutePath()+"/MyBackground.png";
        bm=BitmapFactory.decodeFile(filePath);
        if (bm==null){
            Drawable drawable = getResources().getDrawable(R.mipmap.background);
            drawable.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
            ivBackground.setImageDrawable(drawable);
        }else{
            ivBackground.setImageBitmap(bm);
        }

        //初始化tab和viewpager
        initTab();
    }


    private void loadUser() {
        String userId = getStringFromSp("id");
        Api.config(ApiConfig.GET_USER + "/" + userId, new HashMap<>()).getRequest(requireActivity(), new Callback() {
            @Override
            public void onSuccess(String res) {
                try {
                    UserResponse userResponse = new Gson().fromJson(res, UserResponse.class);
                    userEntity = userResponse.getUserEntity();
                    mHandler.sendEmptyMessage(1);
                } catch (JsonSyntaxException e) {
                    tvNameTop.setText(getString(R.string.load_error));
                    tvName.setText(getString(R.string.load_error));
                }
            }

            @Override
            public void onFailure(Exception e) {
                showToastSync(getString(R.string.check_network));
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                showUser();
            }else if (msg.what == 2){
                //将图片保存到内地存储
                File pictureFile = new File(getContext().getFilesDir().getAbsolutePath()+"/MyBackground.png");
                try {
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    bm.compress(Bitmap.CompressFormat.PNG, 90, fos);
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @SuppressLint("SetTextI18n")
    private void showUser() {
        String name = userEntity.getName();
        String phone = getStringFromSp("account");
        if (name == null || name.equals("")) {
            tvNameTop.setText("用户" + phone);
            tvName.setText("用户" + phone);
        } else {
            tvNameTop.setText(name);
            tvName.setText(name);
        }
        String headUrl = userEntity.getHeadUrl();
        if (headUrl != null && !headUrl.equals("")) {
            Picasso.get().load(headUrl).into(ivHeaderTop);
            Picasso.get().load(headUrl).into(ivHeader);
        }
    }

    private void initTab() {
        String[] titles = {getString(R.string.fragment_three_child_one),
                getString(R.string.fragment_three_child_two)};
        for (String title : titles) {
            mTabEntities.add(new TabEntity(title, 0, 0));
        }
        mFragments.add(new MyTreeHoleFragment());
        mFragments.add(new MyReplyFragment());
        tabLayout.setTabData(mTabEntities);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPage.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        adapter = new ViewPage2Adapter(requireActivity(), mFragments);
        viewPage.setAdapter(adapter);
        viewPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                tabLayout.setCurrentTab(position);
            }
        });
    }


    @SuppressLint({"NonConstantResourceId", "Range"})
    @OnClick({R.id.iv_setting_coll, R.id.iv_setting_tool, R.id.iv_background})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_setting_coll:
            case R.id.iv_setting_tool:
                jumpTo(SettingActivity.class);
                break;
            case R.id.iv_background:
                showDialog();
        }
    }

    private void showDialog() {
        CircleDialog.Builder builder = new CircleDialog.Builder();
        List<String> list = new ArrayList<>();
        list.add("从相册替换");
        list.add("拍照替换");
        builder.setGravity(Gravity.BOTTOM)
                .setWidth(getActivity().getWindowManager().getDefaultDisplay().getWidth())
                .setItems(list, new OnLvItemClickListener() {
                    @SuppressLint("CheckResult")
                    @Override
                    public boolean onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (position == 0) {
                            PictureSelector.create(getActivity())
                                    .openGallery(PictureMimeType.ofImage())
                                    .compress(false)
                                    .maxSelectNum(1)
                                    .minSelectNum(1)
                                    .imageSpanCount(3)
                                    .selectionMode(PictureConfig.MULTIPLE)
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        } else {
                            //获取写的权限
                            RxPermissions rxPermission = new RxPermissions(requireActivity());
                            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                    .subscribe(new Consumer<Permission>() {
                                        @SuppressLint("CheckResult")
                                        @Override
                                        public void accept(Permission permission) {
                                            if (permission.granted){
                                                PictureSelector.create(getActivity())
                                                        .openCamera(PictureMimeType.ofImage())
                                                        .compress(true)
                                                        .forResult(PictureConfig.CHOOSE_REQUEST);
                                            }
                                        }
                                    });
                        }
                        return true;
                    }
                })
                .setNegative("取消", null)
                .show(getChildFragmentManager());
    }


    @Override      //接收返回的地址
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> img= PictureSelector.obtainMultipleResult(data);
                    bm= BitmapFactory.decodeFile(img.get(0).getPath());
                    //保存并显示
                    ivBackground.setImageBitmap(bm);
                    mHandler.sendEmptyMessage(2);
                    break;
            }
        }

    }

}



